var url_search = "/web/api/product/productSale/search_productSale";
var url_attr = "/web/api/product/attribute/get_attribute_all";
var url_addProductSale = "/web/api/product/productSale/add_productSale";
var url_updateProductSale = "/web/api/product/productSale/update_Proudctsale";
var url_saveOrupdate = producturl + url_addProductSale;
$(function () {
    //初始化商品的属性
    var arrt = new ArrtInit();
    arrt.Init(1);
    var product_id = $.getUrlParam("product_id");
    var flag = $.getUrlParam("flag");
    //如果商品id不为空，需要初始化商品详情信息
    if (product_id != undefined && product_id != "" && product_id != null) {
        $("#product_id").val(product_id);
        var oTable = new TableInit();
        oTable.Init(product_id);
        url_saveOrupdate = producturl + url_updateProductSale;
        if (flag == "showInfo") {
            $("#saveOrupdate").hide();
        }
    }
})
var TableInit = function (product_id) {
    var oTableInit = new Object();
    oTableInit.Init = function (product_id) {
        $.ajax({
            url: producturl + url_search,
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                "product_id": product_id,
                "NEED_DO_CHECK": "false"
            },
            success: function (data) {
                if (data != null && data.result.listProductSale.length > 0) {
                    var product_json = data.result.listProductSale;
                    var tablelistProduct = new Array();
                    $.each(product_json, function (index, item) {
                        //商品类型实物、虚拟
                        $("input[name='product_type'][value=" + item.product_type + "]").prop("checked", true);
                        //收货日期设置
                        $("input[name='product_three_type'][value=" + item.three_type + "]").prop("checked", true);
                        if (item.product_type == 200) {
                            getPanelBody();
                            getPanelBodyReciveTime(item.three_type, product_json);
                        }
                        $("input[name='product_type']").each(function () {
                            $(this).prop("disabled", true);
                        });
                        $("input[name='product_three_type']").each(function () {
                            $(this).prop("disabled", true);
                        });
                        //---------------第六个tab---------------------//
                        var attr_product = eval('(' + item.my_attr_json + ')');
                        if (item.product_type == 100) {
                            //虚拟商品
                            $("#virtualProductName").val(item.name);
                            $("#virtualProductPrice").val(item.price.toFixed(2));
                            $("#visualBox").show();
                            $("#productBox").hide();
                            $("#productPanel").hide();
                            $("#productNameBody").hide();
                        } else{
                            console.log(item.ship_template_code);
                            $("#product_name").val(item.name);
                            /*排期模板 配送模板  调接口 带数据*/
                            //排期模板
                            function getscheduleVOList() {
                                var _this = this;
                                //接口请求
                                $.getRequest(producturl+"/web/api/product/productSchedule/searchProductSchedule?NEED_DO_CHECK=false",{
                                    "str" : JSON.stringify({
                                        productCategoryName: "",
                                        productAlias: "",
                                        currentSchedule:"",
                                        scheduleEnd:"",
                                        scheduleStart:""
                                    })
                                },function (res) {
                                    if (res.status == "200") {
                                        //把接口返回的值保存到userList中
                                        _this.productSchedule = res.result;
                                        setscheduleVOList(_this.productSchedule);
                                        console.log(_this.productSchedule);
                                    }
                                });
                            }
                            //模板排期字符拼接
                            function setscheduleVOList(datalist) {
                                var str1="";//定义一个空的字符串
                                var str0="<option value=''>无</option>";
                                for(var n in datalist){
                                    str1+="<option value='"+datalist[n].productCategoryCode+"'>"+datalist[n].productCategoryName+"</option>";
                                };//for循环遍历json数据
                                str = str0+str1;
                                var oTr = document.getElementById("selscheduleVOList");//获取节点
                                oTr.innerHTML = str;//把拼接好的html拼入
                                $("#selscheduleVOList").val(item.product_category_code);
                            }
                            //配送模板
                            function getshippingList() {
                                var _this = this;
                                //接口请求
                                $.ajax({
                                    type: "post",
                                    url: shippingurl + "shippingTemplate.jsonp",
                                    data: {
                                        "str": JSON.stringify({
                                            "id": this.shippingId,
                                            "shippingTemplateName": this.shippingName
                                        })
                                    },
                                    dataType: "jsonp",
                                    error: function (error) {
                                        alert("error:" + error);
                                    },
                                    success: function (res) {
                                        if (res.status == "200") {
                                            //把接口返回的值保存到userList中
                                            _this.shippingList = res.result;
                                            getshippingVOList(_this.shippingList);
                                            console.log(_this.shippingList);
                                        }
                                    }
                                });
                            }
                            //配送模板字符拼接
                            function getshippingVOList(datalist) {
                                var str1="";//定义一个空的字符串
                                var str0="<option value=''>无</option>";
                                for(var n in datalist){
                                    str1+="<option value='"+datalist[n].id+"'>"+datalist[n].shippingTemplateName+"</option>";
                                };//for循环遍历json数据
                                str = str0+str1;
                                var oTr = document.getElementById("distribution_template");//获取节点
                                oTr.innerHTML = str;//把拼接好的html拼入
                                $("#distribution_template").val(item.ship_template_code);
                            }
                            getscheduleVOList();
                            getshippingList();
                            if (attr_product != null) {
                                $("#productPanel").show();
                                $("#immediately").hide();
                                tablelistProduct.push('<tr>');
                                // tablelistProduct.push('<td style="display: none">' + (index + 1) + '</td>');
                                $.each(attr_product, function (index, item2) {
                                    tablelistProduct.push('<td style="vertical-align: middle" class="hidefirst">' + item2.attr_value + '</td>');
                                });
                                var enable = $.getUrlParam('enable'),td='';
                                if (enable == "false") {
                                    td = '<td><input type="text" id="onlynumber" maxlength="8" class="form-control" disabled value="' + item.price.toFixed(2) + '"></td>'
                                    $("#distribution_template").attr("disabled","disabled");
                                    $("#selscheduleVOList").attr("disabled","disabled");
                                }else{
                                    td = '<td><input type="text" id="onlynumber" maxlength="8" class="form-control" value="' + item.price.toFixed(2) + '"></td>'
                                    $("#selscheduleVOList").attr("disabled","disabled");
                                }
                                tablelistProduct.push(td);
                                tablelistProduct.push('</tr>');
                                $("#tbody_attr_list").html(tablelistProduct.join(''));
                                // $(".hidefirst").eq(0).css("display","none");
                            } else {
                                $("#productPanel").show();
                                $("#cycleProduct").hide();
                                $("#ordinaryProductPrice").val(item.price.toFixed(2));
                            }
                        }
                        $("#product_price").val(item.price.toFixed(2));
                        $("#product_basicid").val(item.basic_id);
                        $("#distribution_template").val(item.ship_template_code);
                        $("#selscheduleVOList").val(item.product_category_code);

                    });
                }
            }
        });
    }
    return oTableInit;
}

//初始化收货时间的内容选项
var ArrtInit = function (arrt_id) {
    var arrtInit = new Object();
    arrtInit.Init = function (arrt_id) {
        $.ajax({
            url: producturl + url_attr,
            dataType: 'json',
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            async: false,
            data: {
                "attribute_id": arrt_id,
                "NEED_DO_CHECK": "false"
            },
            success: function (data) {
                if (data != null && data.result.length > 0) {
                    attr_json = data.result;
                    var attrlistProduct = new Array();
                    $.each(attr_json, function (index, item) {
                        $("#attr_product_list").prop("title", item.pid);
                        attrlistProduct.push('<form role="form">');
                        attrlistProduct.push(item.attr_name + ':&nbsp;&nbsp;');
                        var attr_json_childList = item.childList;
                        $.each(attr_json_childList, function (index2, item2) {
                            attrlistProduct.push('<label class="checkbox-inline">');
                            attrlistProduct.push('<input type="checkbox" id="arrt_' + item2.id + '"  value="' + item2.id + '" name="attr_name_check">');
                            attrlistProduct.push(item2.attr_value);
                            attrlistProduct.push('</label>');
                        });
                        attrlistProduct.push('</form>');
                        attrlistProduct.push('<br>');
                    });
                    $("#attr_product_list").html(attrlistProduct.join(''));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("请求错误状态" + XMLHttpRequest.status);

            }
        });
    }
    return arrtInit;
}

function getPanelBody() {
    var three_type = $("input[name='product_three_type']:checked").val();
    if (three_type == "200") {
        $("#reciveTime ").hide();
    } else {
        $("#reciveTime ").show();
        $("#reciveTime div[receiveType='" + three_type + "']").show().siblings().hide();
    }
}

function getPanelBodyReciveTime(three_type, product_json) {
    if (three_type == "100") {
        var jsonDay = eval('(' + product_json[0].presale_desc + ')');
        $("#start_day").val(jsonDay.startday);
        $("#end_day").val(jsonDay.endday);
    }
    if (three_type == "300") {
        var jsonDay = eval('(' + product_json[0].receive_time + ')');
        var dayList = new Array();
        if (jsonDay.length > 0) {
            dayList.push('<label for="" >收货日期：</label>');
            $.each(jsonDay, function (index, item) {
                dayList.push('<span class="delete">');
                dayList.push('<input size="16" type="text" value="' + item.pre_day + '"  class="selStartTime" disabled readonly > <em class="glyphicon glyphicon-remove Multiplication" style="display: none;"></em>');
                dayList.push('</span>');
            });
        }
        var enable = $.getUrlParam('enable');
        if (enable != "false") {
            dayList.push('<img src="images/jiahao.gif" width="16" height="16" style="display: none" id="addReceiveDate">');
        }
        $("#product_receive_time").html(dayList.join(''));
        var date = new Date();
        var nowDate = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
        $("#addReceiveDate").on("click", function () {
            $(this).before('<span class="delete"><input size="16" style="cursor:pointer!important;"type="text" value="" readonly class="selStartTime" > <em class="glyphicon glyphicon-remove Multiplication" ></em> </span>');
            $.jeDate(".selStartTime",{
                format:"YYYY-MM-DD",
                isinitVal:false,
                isTime:true,
                isClear:true,
                minDate:getNowFormatDate()
            });
            $(".Multiplication").off("click").on("click", function () {
                if ($(".Multiplication").length == 1) {
                    return;
                }
                $(this).parent().remove();
            });
        });
    }
    if (three_type == "400") {
        var attr_key = "";
        if ($.trim(product_json[0].attr_keys) != "") {
            attr_key = product_json[0].attr_keys.split("_");
            $("input[name='attr_name_check']").each(function () {
                var attr_value = $(this).val();
                $(this).prop("disabled", true);
                for (key in attr_key) {
                    if (attr_key[key] == attr_value) {
                        $(this).prop("checked", "checked");
                    }
                }
            });
        }
    }
}

function validatePrice( productPrice) {

    distribution_template = $("#distribution_template option:selected").text();
    if (distribution_template == "无") {
        warnInfo("请选择配送模板");
        return ;
    }
    // selscheduleVOList_name = $("#selscheduleVOList option:selected").text();
    // if (selscheduleVOList_name == "无") {
    //     warnInfo("请选择排期模板");
    //     return ;
    // }

    if (productPrice == "") {
        warnInfo("请输入商品价格");
        return false;
    }
    var flg = /^\d+(\.\d+)?$/
    if (isNaN(productPrice)||!flg.test(productPrice)) {
        warnInfo("请输入正确的商品价格");
        return false;
    }
    return true;
}
function generateMyAttrJson(receive_date, receive_times, attr_json) {
    var my_attr_json = new Array();
    $.each(attr_json, function (index, value) {
        $.each(value.childList, function (index, value) {
            if (value.attr_value == receive_date || value.attr_value == receive_times) {
                var jsonInfo = {};
                jsonInfo.id = value.id
                jsonInfo.attr_value = value.attr_value;
                jsonInfo.attr_name = value.attr_name;
                jsonInfo.pid = value.pid;
                my_attr_json.push(jsonInfo);
            }
        });
    });
    return my_attr_json;
}
//保存,编辑商品基本信息
function saveOrupdateProductSale() {
    //验证商品
    // var product_type = $.trim($('input[name="product_type"]:checked').val());
    // if (product_type == "") {
    //     warnInfo("请输入商品类型");
    //     return;
    // }
    var productArray = new Array();
    var product_three_type = $.trim($('input[name="product_three_type"]:checked').val());
    var product_name="";
    var product_type = 200;
    if (product_type == 100) {
        //虚拟商品
        var productInfo = {};
        product_name = $("#virtualProductName").val();
        if (product_name == "") {
            warnInfo("请输入商品名称");
            return ;
        }
        var product_price = $("#virtualProductPrice").val();
        if (!validatePrice(product_price)) {
            return;
        }
        productInfo.name = product_name;
        productInfo.price = product_price;
        productInfo.two_type = "100";
        productArray.push(productInfo);
    } else {
        //实物商品
        if (product_three_type == "") {
            warnInfo("请填写收货时间");
            return;
        }
        product_name = $("#product_name").val();
        if (product_name == "") {
            warnInfo("请输入商品名称");
            return ;
        }
        // productInfo.productCategoryCode = "";
        // productInfo.shipTemplateCode = "";
        // productInfo.productCategoryName = "";
        // productInfo.shipTemplateName = "";

        if (product_three_type == 400) {
            //周期商品
            if(!isChecked("arrt_17")&&!isChecked("arrt_18")&&!isChecked("arrt_19")&&!isChecked("arrt_20")&&!isChecked("arrt_21")&&!isChecked("arrt_22")&&!isChecked("arrt_23")){
                warnInfo("请选择收货日期");
                return;
            }
            if(!isChecked("arrt_6")&&!isChecked("arrt_7")&&!isChecked("arrt_8")&&!isChecked("arrt_9")&&!isChecked("arrt_10")&&!isChecked("arrt_11")){
                warnInfo("请选择收货期数");
                return;
            }
            var flag = true;
            $('#productTable > tbody  tr').each(function () {
                // var product_price = $(this).find('td').eq(3).find('input').val();
                var product_price = $("#onlynumber").val();
                if (!validatePrice(product_price)) {
                    flag = false;
                    return false;
                }
            });
            if(!flag){
                return;
            }
            $('#productTable > tbody  tr').each(function () {
                var receive_date = $(this).find('td').eq(0).html();
                var receive_times = $(this).find('td').eq(1).html();
                var my_attr_json = generateMyAttrJson(receive_date, receive_times, attr_json);
                var product_price = $(this).find('td').eq(2).find('input').val();
                var product_three_type = $.trim($('input[name="product_three_type"]:checked').val());
                var productInfo = {};
                /*x*/
                var distribution_template = $("#distribution_template option:selected").text();
                var selscheduleVOList_name = $("#selscheduleVOList option:selected").text();
                var distribution_templatecode = $("#distribution_template option:selected").val();
                var selscheduleVOList_namecode = $("#selscheduleVOList option:selected").val();
                productInfo.shipTemplateName = distribution_template;
                productInfo.productCategoryName = selscheduleVOList_name;
                productInfo.shipTemplateCode = distribution_templatecode;
                productInfo.productCategoryCode = selscheduleVOList_namecode;
                /*x*/
                productInfo.price = product_price;//默认
                productInfo.three_type = product_three_type;
                productInfo.two_type = "200";
                productInfo.my_attr_json = my_attr_json;
                productInfo.attr_json = getAttrJsonAll($("#attr_product_list").prop("title"));
                productArray.push(productInfo);
            });
        } else {
            //非周期商品
            if (product_three_type == "100") {//用户预订
                // var start_day = $.trim($("#start_day").val());
                // var end_day = $.trim($("#end_day").val());
                // if (start_day == "" || end_day == "") {
                //     warnInfo("请输入用户预定信息");
                //     return;
                // }
                //
                // if(eval(end_day)<eval(start_day))
                // {
                //     warnInfo("结束天数不能小于开始天数");
                //     return;
                // }
            } else if (product_three_type == "300") {//指定日期
                var selStartTime = $("input.selStartTime");
                var flag = false;
                $.each(selStartTime, function (index, item) {
                    if ($.trim(item.value) != "") {
                        flag = true;
                    }
                });
                if (flag == false) {
                    warnInfo("请输入收货日期");
                    return;
                }
            }
            var product_price = $("#ordinaryProductPrice").val();
            if (!validatePrice(product_price)) {
                return;
            }
            var productInfo = {};
            var distribution_template = $("#distribution_template option:selected").text();
            var selscheduleVOList_name = $("#selscheduleVOList option:selected").text();
            var distribution_templatecode = $("#distribution_template option:selected").val();
            var selscheduleVOList_namecode = $("#selscheduleVOList option:selected").val();
            productInfo.shipTemplateName = distribution_template;
            productInfo.productCategoryName = selscheduleVOList_name;
            productInfo.shipTemplateCode = distribution_templatecode;
            productInfo.productCategoryCode = selscheduleVOList_namecode;

            productInfo.price = product_price;//默认
            productInfo.three_type = product_three_type;
            productInfo.two_type = "100";
            var selStartTime = $("input.selStartTime");
            var receive_time_array = new Array();
            if (product_three_type == "100") {//用户预订
                var presale_desc_map = {
                    "startday": $.trim($("#start_day").val()),
                    "endday": $.trim($("#end_day").val())
                };
                productInfo.presale_desc = presale_desc_map;
            } else if (product_three_type == "300") {//指定日期
                var receiveDateArray = new Array();
                $.each(selStartTime, function (index, item) {
                    if ($.trim(item.value) != "" && receiveDateArray.indexOf(item.value)== -1) {
                        var receive_time_map = {};
                        receive_time_map.pre_day = item.value;
                        receive_time_array.push(receive_time_map);
                        receiveDateArray.push(item.value);
                    }
                });
                productInfo.receive_time = receive_time_array;
            }
            productArray.push(productInfo);
        }
    }
    $.each(productArray,function(index,productInfo){
        var product_id = $.trim($("#product_id").val());
        var product_basicid = $("#product_basicid").val();
        productInfo.id = product_id;
        productInfo.product_type = 200;
        productInfo.name = product_name;
        productInfo.basic_type = "200";
        productInfo.keyword = "";
        productInfo.title = "";
        productInfo.barcode = "";
        if (product_basicid != "") {
            productInfo.basic_id = product_basicid;
        }
    });
    $.ajax({
        url: url_saveOrupdate,
        dataType: 'json',
        type: 'post',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        async: false,
        data: {
            "product_param": JSON.stringify(productArray),
            "NEED_DO_CHECK": "false"
        },
        success: function (data) {
            console.log(data);
            if (data != null && data.status == "200") {
                alert("编辑成功");
                //window.location.href = "index.html";
                window.history.back();
            } else {
                alert(data.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("请求错误状态" + XMLHttpRequest.status);
        }
    });
}


function getAttrJsonAll(attr_id) {
    var attr_json = null;
    $.ajax({
        url: producturl + url_attr,
        dataType: 'json',
        type: 'post',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        async: false,
        data: {
            "attribute_id": attr_id,
            "NEED_DO_CHECK": "false"
        },
        success: function (data) {
            if (data != null && data.result != null) {
                attr_json = data.result;
            }
        }
    });
    return attr_json;
}

function warnInfo(errorMsg){
    bootbox.alert({
        size: "small", title: "错误信息", message: errorMsg, callback: function () {
        }
    });
}


